package leetcode100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class lc040 {
    public static void main(String[] args) {
        int[][] intervals = new int[][]{{1, 3}, {4, 6}, {5, 7}};
        int[][] merge = new lc040().merge(intervals);
        System.out.println("Arrays.deepToString(merge) = " + Arrays.deepToString(merge));
    }

    public int[][] merge(int[][] intervals) {
        List<int[]> res = new ArrayList<>();
        Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
//        System.out.println("Arrays.deepToString(merge) = " + Arrays.deepToString(intervals));
        res.add(intervals[0]);
        for (int i = 1; i < intervals.length; i++) {
            int[] cur = intervals[i];
            int[] last = res.get(res.size() - 1);

            if (cur[0] <= last[1]) {
                last[1] = Math.max(cur[1], last[1]);
            } else {
                res.add(cur);
            }

        }

        int[][] res2 = new int[res.size()][2];

        for (int i = 0; i < res.size(); i++) {

            res2[i] = res.get(i);
        }

        return res.toArray(new int[res.size()][]);
    }
}
